package com.jt.auth.service.impl;

import com.jt.auth.pojo.User;
import com.jt.auth.service.RemoteUserService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.AuthorityUtils;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.stereotype.Service;

import java.util.List;

/**
 * 该类从sso-system服务中获取用户信息
 * 并封装返回，交给认证管理器去完成密码的操作
 */
@Slf4j
@Service
public class UserServiceDetailImpl  implements UserDetailsService {
    @Autowired //远程服务调用接口
    private RemoteUserService remoteUserService;
    /**
     * 该方法，当点击登入按钮之后就会执行该方法，不进入controller
     * @param username 来自客户端用户提交的用户名
     * @return
     * @throws UsernameNotFoundException
     */
    @Override
    public UserDetails loadUserByUsername(String username) throws UsernameNotFoundException {
       //基于用户名查找用户信息是否存在
        User user = remoteUserService.selectUserByName(username);
        if (user == null){
            throw new UsernameNotFoundException("user is not exist !");
        }
        //基于用户id查找用户权限（登入用户不一定可以访问全部）
        List<String> permissions = remoteUserService.selectUserPermissions(user.getId());
        log.debug("permission : {}",permissions.toString());
        //封装查询结果并返回
        return new org.springframework.security.core.userdetails.User(user.getUsername(), user.getPassword(),
                AuthorityUtils.createAuthorityList(permissions.toArray(new String[]{})));
    }
}
